package com.onland.dfish.controller;

import com.onland.dfish.entity.ResponseData;
import com.onland.dfish.entity.Sort;
import com.onland.dfish.service.ISortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理视频分类请求控制器
 */
@Controller
@RequestMapping("sort")
public class SortController {
    @Autowired
    private ISortService sortService;

    /**
     * 创建分类
     * @param s
     * @return
     */
    @PostMapping("create")
    public String createSort(Sort s){
        sortService.createSort(s);
        return "redirect:/sort/create_sort.jsp";
    }

    /**
     * 根据视频分类等级加载分类数据
     * @param level
     * @return
     */
    @GetMapping("load_by_level")
    @ResponseBody
    public List<Sort> loadSortData(int level)
    {
        return sortService.querySort(level);
    }
    /**
     * 根据父视频分类ID,查询子视频分类
     * @param pId
     * @return
     */
    @GetMapping("load_sub_type")
    @ResponseBody
    public List<Sort> loadSubSortData(@RequestParam("p_id") int pId)
    {
        return sortService.querySubSort(pId);
    }



    /***
     * 查询视频分类
     * @param level
     * @param model
     * @return
     */
   @PostMapping("query")
    public  String querySort(int level, Model model)
    {
        List<Sort> sortList=sortService.querySort(level);
        model.addAttribute("sortList",sortList);
        return "/sort/query_sort.jsp";
    }

    /**
     * 根据ID删除视频分类
     * @param id
     * @return
     */
    @GetMapping("remove")
    @ResponseBody
    public  int removeSort(int id)
    {
        return sortService.removeSort(id);
    }

    /**
     * 根据视频分类ID加载分类数据
     * @param id
     * @return
     */
    @GetMapping("load_by_id")
    @ResponseBody
    public Map<String,Object> loadById(int id)
    {
        Map<String,Object> map=new HashMap<>();
        Sort sort=sortService.getSort(id);
        if(sort==null)
        {
            //未查询到数据
            return map;
        }
        map.put("sort",sort);
        int level=sort.getLevel();
        if(2==level){
            List<Sort> sortList=sortService.querySort(1);
            map.put("sortList",sortList);
        }
        return map;
    }

    /**
     * 修改分类
     * @param s
     * @return
     */
    @PostMapping("modify")
    public String modifySort(Sort s){
        int rows=sortService.modifySort(s);
        return "redirect:/sort/modify_result.jsp?rows="+rows;
    }

    /**
     * 加载所有的分类数据
     * @return
     */
    @GetMapping("all_sort")
    @ResponseBody
    public ResponseData  loadAll(){
        List<Sort> sortList=sortService.selectAll();
        return ResponseData.SUCCESS(sortList);
    }
}
